package com.gxc.authcore.system.util;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gxc.authcore.system.cache.UserCache;
import com.gxc.authcore.system.domain.Role;
import com.gxc.authcore.system.domain.User;

/**
 * 存放线程局部变量，在每个线程中都会有一个互不影响的副本
 */
public class CurrentUtil {

	/**
	 * 当前线程request
	 */
	private static final ThreadLocal<HttpServletRequest> currentRequest = new ThreadLocal<HttpServletRequest>();

	/**
	 * 当前线程response
	 */
	private static final ThreadLocal<HttpServletResponse> currentResponse = new ThreadLocal<HttpServletResponse>();

	/**
	 * 当前线程authid
	 */
	private static final ThreadLocal<String> currentAuthid = new ThreadLocal<String>();

	/**
	 * 当前线程authCache
	 */
	private static final ThreadLocal<AuthInfo> currentAuthInfo = new ThreadLocal<AuthInfo>();

	public static void setRequest(HttpServletRequest request) {
		currentRequest.set(request);
	}

	public static HttpServletRequest getRequest() {
		return currentRequest.get();
	}

	public static void setResponse(HttpServletResponse response) {
		currentResponse.set(response);
	}

	public static HttpServletResponse getResponse() {
		return currentResponse.get();
	}

	public static String getAuthid() {
		return currentAuthid.get();
	}

	public static void setAuthid(String authid) {
		currentAuthid.set(authid);
	}

	public static AuthInfo getAuthInfo() {
		return currentAuthInfo.get();
	}

	public static void setAuthInfo(AuthInfo authInfo) {
		currentAuthInfo.set(authInfo);
	}

	public static String getUserId() {
		if (CurrentUtil.getAuthInfo() != null) {
			return CurrentUtil.getAuthInfo().getUserid();
		}
		return null;
	}

	public static User getAuthUser() {
		if (CurrentUtil.getAuthInfo() != null) {
			String user_id = CurrentUtil.getAuthInfo().getUserid();
			return UserCache.getUser(user_id);
		}
		return null;
	}

	public static List<Role> getRoleList() {
		if (CurrentUtil.getAuthInfo() != null) {
			String user_id = CurrentUtil.getAuthInfo().getUserid();
			return UserCache.getRoleList(user_id);
		}
		return null;
	}

}
